<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>批量拆箱</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<style type="text/css">
		.tmdyTable td{border:1px solid #00000080;} 
	</style>
</head>
<script type="text/javascript">
	$(document).on('keydown','[lay-id="productAddTable"] .layui-table-edit',function(e){
		var td = $(this).parent('td'),
		tr = td.parent('tr'),
		trs = tr.parent().parent().find('tr'),
		tr_index = tr.index(),
		td_index = td.index(),
		td_last_index = tr.find('[data-edit="text"]:last').index(),
		td_first_index = tr.find('[data-edit="text"]:first').index();
		switch(e.keyCode){
			case 13:
			case 39:
				td.nextAll('[data-edit="text"]:first').click();
				if(td_index == td_last_index){
					tr.next().find('td').eq(td_first_index).click();
					if(tr_index == trs.length-1){
						trs.eq(0).find('td').eq(td_first_index).click();
					}
				}
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
			case 37:
				td.prevAll('[data-edit="text"]:first').click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
			case 38:
				tr.prev().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
			case 40:
				tr.next().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
				break;
		} 
	})
</script>
<body class="layui-anim layui-anim-up">
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>批量拆箱</cite>
        </a>
      </span>
</div>
<div class="x-body">
	
	<!-- 列表页上方的搜索栏 及 列表 -->
	<div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<input id="gys" hidden="hidden">
						<input id="getIndex" hidden="hidden">
						<input class="layui-input" name="ordernum" id="ordernumc" placeholder="请输入拆箱计划单号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
					<%-- <td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="sendCompanyc" name="sendCompany">
								<option value="">请选择供应商</option>
								<c:forEach items="${customer_type0}" var="customer">
									<option value="${customer.id}">${customer.customer_name}</option>
								</c:forEach>
							</select>
						</div>
					</td> --%>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
	</div>
	<xblock>
		<button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
		<button class="layui-btn layui-btn-danger" id="dels"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	</xblock>
	<table class="layui-hide" id="tableList" lay-filter="tableList"></table>
</div>


<div id="subDiv" hidden="hidden">
	<xblock>
		<button class="layui-btn layui-btn-danger" id="delete2"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	</xblock>
	<table class="layui-hide" id="tableDetails" lay-filter="tableDetails"></table>
</div>

<script type="text/html" id="rowToolbar">
	<a class="layui-btn layui-btn-xs" lay-event="confirmor"><i class="layui-icon layui-icon-ok"></i>确认</a>
</script>

<script type="text/html" id="rowToolbar2">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete1"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>

<script type="text/html" id="productAddRowToolbar">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="proDel">删除</a>
</script>


<!-- 产品选择框 -->
<div id="productDiv" hidden="hidden">
	<form class="layui-form">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<td>
							<input class="layui-input" name="materiel_num" id="materiel_numc" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			&emsp;<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" id="selectMateriel" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
		<table id="productTable" lay-filter="productTable"></table>
		<xblock>
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>
		</xblock>
	</form>
</div>

<!-- 新增框 -->
<div id="addDivID" hidden="hidden">
	<form class="layui-form" id="addFormID">
		<xblock>
			<table>
				<tr>
					<td><label class="layui-form-label">拆箱单号</label></td>
					<td>
						<input readonly class="layui-input" id="ordernum" name="ordernum" style="width: 160px; color: gray">
						<input type="hidden" id="id" name="id">
					</td>
					<td>
						<label class="layui-form-label">供应商</label></td>
					<td>
						<div class="layui-input-inline" style="width:160px">
							<select class="layui-input" name="sendCompany" id="sendCompany" lay-filter="sendCompany">
								<option value="" selected="selected">请选择供应商</option>
								<c:forEach items="${customer_type0}" var="customer" >
									<option value="${customer.id}">${customer.customer_name}</option>
								</c:forEach>
							</select>
						</div>
						<div class="layui-inline" style="margin-top: 10px;">
							<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
						</div>
						<input type="hidden" id="text">
					</td>
					<td>
                        <label class="layui-form-label">紧急程度</label>
                    </td>
                    <td>
						<div class="layui-input-inline" style="width:160px">
							<select class="layui-input" name="remark" id="remark" lay-filter="remark">
								<option value="0" selected="selected">一般</option>
								<option value="1" selected="selected">中等</option>
								<option value="2" selected="selected">紧急</option>
							</select>
						</div>
						<div class="layui-inline" style="margin-top: 10px;">
							<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
						</div>
						<input type="hidden" id="text">
					</td>
					<td>
                        <label class="layui-form-label"></label>
                    </td>
                    <td>
                        <button type="button" class="layui-btn layui-btn-normal" onclick="addProduct()">选择物料</button>
                    </td>
				</tr>
				<tr style="height: 10px"></tr>
			</table>
		</xblock>
		<table id="productAddTable" lay-filter="productAddTable"></table>
		<xblock>
			<div align="center">
				<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm">提交</button>
				&emsp;&emsp;&emsp;&emsp;
				<button class="layui-btn layui-btn-primary">取消</button>
			</div>
		</xblock>
	</form>
</div>

<script type="text/javascript">
    var table;
    layui.use(['table','layer','upload','form','laydate'], function(){
        table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;

        var $ = layui.jquery, active = {
            reload:function () {
                var ordernum = $.trim($("#ordernumc").val());
               // var sendCompany = $.trim($("#sendCompanyc").val());
                table.reload('contenttable',{
                    method:'get',
                    where:{
                    	ordernum:ordernum
                       /*  ,sendCompany:sendCompany */
                    }
                    ,page: {
                    	//重新从第 1 页开始
                        curr: 1
                    }
                });
            }
        }
        
      	//llm新增，添加物料的查询
        $(document).on('click','#selectMateriel',function(){
     		var materiel_num=$('#materiel_numc').val();
     		var table = layui.table;
     		var verify = /^[0-9,]*$/;
    		//if(verify.test(materiel_num)){
    			var split = materiel_num.split(',')
    			if(split.length <= 5){
    				table.reload('productTable',{
						method:'post'
						,where:{"materielNum":materiel_num}
		         		,page: {
		                    curr: 1//重新从第 1 页开始
		                }
					});
    			}else{
    				layer.msg("最多可同时查5个！");
    			}
    		/* }else{
    			layer.msg("只能输入数字和英文逗号！");
    		} */
    	}) 
    	
      	//点击行checkbox选中
	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
	        var index = $(this).attr('data-index');
	        var tableBox = $(this).parents('.layui-table-box');
	        //存在固定列
	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
	        } else {
	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
	        }
	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
	        if (checkCell.length>0) {
	            checkCell.click();
	        }
	    });
	
	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
	        e.stopPropagation();
	    });
        
        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        /* 拆箱计划单列表 */
        table.render({
            elem: '#tableList'
            ,url:'${pageContext.request.contextPath }/simple/list.do'
            ,title: 'machineList'
            ,id :'contenttable'
            ,limits:[10,20,30]
            ,toolbar: '#toolbar'
            ,cols: [
                [{type: 'checkbox',fixed: 'left'},
                    {field:'id',title:'NO',sort: true,width: 50,type:'numbers',align:'center'},
                    {field: 'ordernum',title: '拆箱计划单号',align:'center'},
                    {field: 'userName',title: '创建人',align:'center'},
                    {field: 'createDate',title: '创建时间',align:'center',},
                    {field: 'unpackMan',title: '拆箱人',align:'center'},
                    {field: 'unpackDate',title: '拆箱时间',align:'center'},
                    {field: 'state',title: '状态',align:'center'
                        ,templet: function(d){
                            var value = d.state;
                            if(value == 0){
                                value = "未拆箱"
                            }else if(value == 1){
                                value = "未完成"
                            }else if(value == 2){
                                value = "已确认"
                            }
                            return value;
                        }
                    },
                    {field: 'remark',title: '紧急程度',align:'center'
                        ,templet: function(d){
                            var value = d.remark;
                            if(value == 0){
                                value = "一般"
                            }else if(value == 1){
                                value = "中等"
                            }else if(value == 2){
                                value = "紧急"
                            }
                            return value;
                        }
                    },
                    ,{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar', width:80, align: 'center'}
                ]
            ]
            ,page: true
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold'
                })
            }
        });
        
        /* 打印标签 */
        table.render({
            elem: '#bqtable'
            ,title: '条码表'
            ,cols: [[
				 {type: 'checkbox',fixed: 'left'},
                 {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                 {field:'materiel_name', title:'供应商', align:'center', width: 100
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.unpackDetal	!= null){
		                     if(d.unpackDetal.materiel	!= null){
	                    	 	value = d.unpackDetal.materiel.customer_name
                     		 }
	                     }
	                     return value;
                 	}
                 },
                 {field:'materiel_num', title:'SAP_QAD', align:'center', width: 150
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.unpackDetal	!= null){
		                     if(d.unpackDetal.materiel	!= null){
	                    	 	value = d.unpackDetal.materiel.materiel_num
                     		 }
	                     }
	                     return value;
                 	}
                 },
                 {field:'materiel_name', title:'中文名称', align:'center', width: 200
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.unpackDetal	!= null){
		                     if(d.unpackDetal.materiel	!= null){
	                    	 	value = d.unpackDetal.materiel.materiel_name
                     		 }
	                     }
	                     return value;
                 	}
                 },
                /*  {field:'brevity_num', title:'零件号', align:'center', width: 200
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.unpackDetal	!= null){
	                    	 if(d.unpackDetal.materiel	!= null){
	                    	 	value = d.unpackDetal.materiel.brevity_num
	                     	}
	                     }
	                     return value;
                 	}
                 }, */
                 {field:'packing_quantity', title:'包装数量', width: 100, align:'center'
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.unpackDetal	!= null){
	                    	 if(d.unpackDetal.materiel	!= null){
	                    	 	value = d.unpackDetal.materiel.packing_quantity
	                     	}
	                     }
	                     return value;
                 	}
                 },
                 {field:'pici', title:'批次', align:'center', width: 100
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.unpackDetal	!= null){
	                    	 value = d.unpackDetal.pici
	                     }
	                     return value;
                 	}
                 },
                 {field:'code', title:'条码', align:'center', width: 200},
                 {field:'num', title:'数量', align:'center', width: 80,},
             ]]
            ,page: false
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
        
        /*=======================点击拆箱计划的下表=======================*/
        table.on('row(tableList)', function(obj){
        	$("#gys").val(obj.data.sendCompany);
        	$("#subDiv").show();
            var data = obj.data;
            table.render({
                elem: '#tableDetails'
                ,url:'${pageContext.request.contextPath }/unpackDetal/list.do?ordernum='+data.ordernum
                ,toolbar: '#toolbar'
                ,title: '明细表'
                ,id :'contenttableDetails'
                ,limits:[10,20,30]
                ,cols: [[
                    {type: 'checkbox',fixed: 'left'},
                    {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                    {field:'mid', title:'物料id', align:'center', hide:true},
                    {field:'materiel_num', title:'SAP/QAD', align:'center',width: 200,},
                    {field:'materiel_name', title:'中文名称', align:'center', width: 300,},
                   /*  {field:'brevity_num', title:'零件号', align:'center', width: 300,}, */
                    {field:'pici', title:'批次', width: 200, align:'center'},
                    {field:'znum', title:'需拆箱总数（个）', align:'center', width: 200},
                    {field:'specs', title:'翻包规格(个)', align:'center', width: 200},
                    {field:'unum', title:'拆箱数量(个)', align:'center'},
                ]]
                ,page: true
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
            });
        });

        table.render({
            elem: '#productAddTable'
            ,defaultToolbar:['filter', 'print']
            ,cols: [[
                {type: 'checkbox',fixed: 'left'},
                {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                {field:'mid', title:'mid', align:'center', hide:true},
                {field:'materiel_num', title:'SAP/QAD', align:'center', width:100},
                {field:'materiel_name', title:'中文名称', align:'center', width:260},
               /*  {field:'brevity_num', title:'零件号', align:'center', width:150}, */
                {field:'packing_quantity', title:'包装数量', align:'center', width: 85},
               	{field:'mBatch', title:'<span style="color: red">批次</span>', align:'center', width: 95},
               	{field:'mNum',title: '库存数量',align:'center'},
                {field:'znum', title:'<span style="color: red">需拆总数(个)</span>', edit: 'text', align:'center', width: 110},
                {field:'specs', title:'<span style="color: red">翻包规格(个)</span>', edit: 'text', align:'center', width: 110},
            	{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar2',width:100, align: 'center'}
            ]]
            ,limit:Number.MAX_VALUE
            ,page: false
            ,height: 400
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
        
        //监听行工具事件
        table.on('tool(productAddTable)', function(obj){
            var data = obj.data;
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            //单个删除
            if(obj.event === 'delete1'){
                layer.confirm('确定删除吗？', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                });
            }
        });
        
        //监听收货计划管理的编辑事件
        table.on('tool(tableList)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                if(data.state != 0){
                    toastr.warning("对不起，已收货的数据不能修改！");
                    return;
                }
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['1100px', '640px'] 	//宽  高
                    ,title: '编辑'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                        $("#id").val(data.id)
                        $("#receiveNumber").val(data.receiveNumber)
                        $("#sendNumber").val(data.sendNumber)
                        $("#sendCompany").val(data.sendCompany)
                        $("#sendName").val(data.sendName)
                        $("#sendDate").val(data.sendDate)
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'receiveNumber='+data.receiveNumber,
                            url:'${pageContext.request.contextPath}/receiveDetail/queryAllByMution.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                                newData = data;
                            }
                        });
                        table.reload('productAddTable',{
                            data : newData
                        });
                        form.render();
                    }
                });
            }else if(obj.event === 'confirmor'){
            	if(data.state == 0){
                    toastr.warning("对不起，未拆箱的数据不能确认！");
                }else if(data.state == 2){
                	toastr.warning("对不起，已确认的数据不能再次确认！");
                }else{
                	$.ajax({
                        type:'post',
                        data:'id='+data.id,
                        url:'${pageContext.request.contextPath}/jyyUnpacking/updateStatus.do',
                        dataType: 'JSON',
                        async: false,
                        success:function (data) {
                            if(data > 0){
                            	toastr.success('操作成功');
                            }else if(data = -1){
                            	toastr.warning('对不起，您没有此权限，只有班长进行此操作');
                            }else if(data = -2){
                            	toastr.warning('对不起，当前登录信息已失效，请重新登录');
                            }else{
                            	toastr.error('操作失败');
                            }
                            setTimeout(function(){
                                window.location.reload();
                            },1000);
                        }
                    });
                }
            }
        });


        /**
         * 添加弹框中，选择物料后，点提交，带回的操作
         */
        form.on('submit(productform)', function (result) {
            var flag;
            var oldData = table.cache["productAddTable"];
            var checkStatus = table.checkStatus('productTable')
            //选中的物料
            var data = checkStatus.data;
            for (var j = 0; j < data.length; j++) {
                for (var k = 0; k < oldData.length; k++) {
                    if (oldData[k].mid == data[j].mid) {
                        flag = 0;
                    }
                }
            }
            if (flag != 0) {
                for (var i = 0; i < data.length; i++) {
                    oldData.push(data[i]);
                }
            } else {
                toastr.warning("记录已经存在，不能重复添加");
            }
            table.reload('productAddTable',{
                data : oldData
            });
            $('[lay-id="productAddTable"] [data-edit="text"]:first').click();
            layer.close(productIndex)
            return false;
        });

        /**
         * 新增--提交
         */
        form.on('submit(addForm)', function (data) {
        	flag = 0;
            var ordernum = $("#ordernum").val();
            //获取明细中数据
            var oldData = table.cache["productAddTable"];
            var data = oldData.filter(function(item){
                var re = /^[0-9]\d*$/ ;
                return item.specs == "" || item.specs == undefined || !re.test(item.specs) || item.znum == "" || item.znum == null || item.znum == undefined || !re.test(item.znum) ;
            })
            if(oldData.length == 0){
                toastrStyle();
                toastr.warning("请添加物料详情！");
                return false;
            }else if(data.length > 0){
                toastrStyle();
                toastr.warning("请输入正确的 需拆箱总数 和 拆箱规格 (大于0的正整数)");
                return false;
            }else{
            	
            	for (var i = 0; i < oldData.length; i++) {
                    if(oldData[i].znum >  oldData[i].mNum) {
                    	var j = i+1;
                   	 	toastr.warning("第"+j+"条数据，需拆箱数量 大于 库存数量");
                   		return false;
                    }else {
                    	flag = 1;
                    }
            	}
            	
            	if(flag == 1) {
            		//获取明细表中的所有记录，遍历，循环添加
                    for (var i = 0; i < oldData.length; i++) {
                        var mid = oldData[i].mid;
                        var specs = oldData[i].specs;
                        var znum = oldData[i].znum;
                        var pici = oldData[i].mBatch;
                        //添加收货明细
                        $.ajax({
                            url: '${pageContext.request.contextPath}/unpackDetal/insert2.do' ,
                            type: 'post',
                            data: {ordernum:ordernum, mid:mid, specs:specs, znum:znum, pici:pici},
                            async: false,
                            dataType:'JSON',
                            success: function (result) {
                                if (result > 0) {
                                    if(i == oldData.length - 1) {
                                        var title = "新增";
                                        var url = '${pageContext.request.contextPath}/simple/insert.do';
                                        var id = $.trim($("#id").val());
                                        if(id != "" && id != null && id != 'undefined'){
                                            var url = '${pageContext.request.contextPath}/simple/update.do';
                                            title = "修改";
                                        }

                                        //添加收货单
                                        $.ajax({
                                            url : url,
                                            data: $("#addFormID").serialize(),
                                            cache : false,
                                            async: false,
                                            type : "post",
                                        }).done(
                                            function(res) {
                                                if (res > 0) {
                                                    toastr.success(title+'成功');
                                                    setTimeout(function(){
                                                        window.location.reload();
                                                        $("#reset").click();
                                                    },1000);
                                                }
                                            }
                                        ).fail(
                                            function(res) {
                                                toastr.error(title+'失败！');
                                                setTimeout(function(){
                                                    location.reload();
                                                },1000);
                                            }
                                        )
                                    }

                                }else{
                                    toastr.warning("对不起，明细添加失败！");
                                }
                            },
                            error: function (data) {
                                toastr.error("对不起，明细添加错误！");
                            }
                        })
                    }
            	}
                return false;
            }
        });
        
      	/* ============ */
        //增加
        $("#add").click(function(){
            layer.open({
                type: 1 					//Page层类型
                ,area: ['1100px', ''] 			//宽  高
                ,title: '新增'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: $('#addDivID')
                ,end: function () {
                    var formDiv = document.getElementById('addDivID');
                    formDiv.style.display = '';
                }
                ,success: function(){
                    var timestamp = (new Date()).getTime();
                    $("#ordernum").val("C-"+timestamp);

                    $("#sendCompany").val("")
                    form.render();
                    
                    table.reload('productAddTable',{
                        data : new Array()
                    });
                }
            });
        });
        
        //llm 监听行内编辑
        table.on('edit(productAddTable)', function(obj){
        	
            var data = obj.data;
            znum = data.znum
            mNum = data.mNum
           	if(znum > mNum) {
           		layer.alert("对不起，拆箱数量不能大于库存可拆箱数量！");
           	}
           	
        	//设置jQuery对象
        	LayUIDataTable.SetJqueryObj($);
        	//隐藏列-单列模式
            LayUIDataTable.HideField('num');
         	//隐藏列-多列模式
            LayUIDataTable.HideField(['num','match_guest']);
            var currentRowDataList = LayUIDataTable.ParseDataTable(function (index, currentData, rowData) {
            	$("#getIndex").val(index);
            })
            /* ========================== */
        	var fieldValue = obj.value, //改变后的值
	    	 	rowData = obj.data, 	//得到所在行所有键值
             	fieldName = obj.field; 	//得到字段
           	var sum = 0;
            if(typeof(rowData.sendNum) == "string"){
           		if(typeof(rowData.singleNum) == "string"){
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity)  + parseInt(rowData.singleNum))
           		} else {
	           		sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity));
           		}
           	}
            var opt = rowData.receiveNum;
            opt = sum;
            var allTr = $("#addFormID").find(".layui-table tbody").eq(0).find("tr");
           	for(var i = 0; i < allTr.length; i++){
				if($("#getIndex").val() == i){
					allTr.eq(i).children("td").eq(11).children('div').html(opt);
           		}
          	}
           	
           	
        });
	    	
        //收货计划单批量删除
        $("#dels").click(function() {
            var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length == 0){
                toastr.warning("请至少选择一条记录！");
            }else{
                var ids = "";
                for(var i=0;i<data.length;i++){
                    if(data[i].state != 0){
                        toastr.warning("对不起，已拆箱的数据不能删除！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    }else{
                        ids += "," + data[i].id;
                    }
                }
                layer.confirm('确定删除吗？', function(index){
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/jyyUnpacking/delete.do',
                        data:{"ids":ids},
                        success:function(data){
                            if(data > 0){
                                toastr.success("删除成功！");
                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                    //关闭模态框
                                    //父页面刷新
                                    window.location.reload();
                                },2000);
                            } else {
                                toastr.warning("删除失败！");
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
        });
        
      	//收货计划单详细批量删除
        $("#delete2").click(function() {
        	//获取父表的选中行
			var checkStatusParent = table.checkStatus('contenttable')
            var dataParent = checkStatusParent.data;
            var checkStatus = table.checkStatus('contenttableDetails')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length == 0){
                toastr.warning("请至少选择一条记录！");
            } else {
                var ids = "";
                for(var i = 0; i < data.length; i++) {
                    if(dataParent[i].state != 0){
                        toastr.warning("对不起，已收货的数据不能删除！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    } else {
                        ids += "," + data[i].id;
                    }
                }
                layer.confirm('确定删除吗？', function(index){
                    $.ajax({
                        type : 'post',
                        url : '${pageContext.request.contextPath }/unpackDetal/delete.do',
                        data : {"ids":ids},
                        success : function(data){
                            if(data > 0) {
                                toastr.success("删除成功！");
                                setTimeout(function(){  
                                    window.location.reload();
                                },2000);
                            } else {
                                toastr.warning("删除失败！");
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
        });
      
		//表格行折叠方法
        function collapseTable(options) {
            var trObj = options.elem;
            if (!trObj) {
                return;
            }
            var accordion = options.accordion,
                success = options.success,
                content = options.content || '';
            var tableView = trObj.parents('.layui-table-view'); //当前表格视图
            var id = tableView.attr('lay-id'); //当前表格标识
            var index = trObj.data('index'); //当前行索引
            var leftTr = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + index + '"]'); //左侧当前固定行
            var rightTr = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + index + '"]'); //右侧当前固定行
            var colspan = trObj.find('td').length; //获取合并长度
            var trObjChildren = trObj.next(); //展开行Dom
            var indexChildren = id + '-' + index + '-children'; //展开行索引
            var leftTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + indexChildren + '"]'); //左侧展开固定行
            var rightTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + indexChildren + '"]'); //右侧展开固定行
            var lw = leftTr.width() + 15; //左宽
            var rw = rightTr.width() + 15; //右宽
            //不存在就创建展开行
            if (trObjChildren.data('index') != indexChildren) {
                //装载HTML元素
                var tr = '<tr data-index="' + indexChildren + '"><td colspan="' + colspan + '"><div style="height: auto;padding-left:' + lw + 'px;padding-right:' + rw + 'px" class="layui-table-cell">' + content + '</div></td></tr>';
                trObjChildren = trObj.after(tr).next().hide(); //隐藏展开行
                var fixTr = '<tr data-index="' + indexChildren + '"></tr>';//固定行
                leftTrChildren = leftTr.after(fixTr).next().hide(); //左固定
                rightTrChildren = rightTr.after(fixTr).next().hide(); //右固定
            }
            //展开|折叠箭头图标
            trObj.find('td[lay-event="collapse"] i.layui-colla-icon').toggleClass("layui-icon-right layui-icon-down");
            //显示|隐藏展开行
            trObjChildren.toggle();
            //开启手风琴折叠和折叠箭头
            if (accordion) {
                trObj.siblings().find('td[lay-event="collapse"] i.layui-colla-icon').removeClass("layui-icon-down").addClass("layui-icon-right");
                trObjChildren.siblings('[data-index$="-children"]').hide(); //展开
                rightTrChildren.siblings('[data-index$="-children"]').hide(); //左固定
                leftTrChildren.siblings('[data-index$="-children"]').hide(); //右固定
            }
            success(trObjChildren, indexChildren); //回调函数
            heightChildren = trObjChildren.height(); //展开高度固定
            rightTrChildren.height(heightChildren + 115).toggle(); //左固定
            leftTrChildren.height(heightChildren + 115).toggle(); //右固定
        }
    });

    /*================点击选择物料的弹框================*/
    function addProduct (){
        if ($("#sendCompany").val() == "" || $("#sendCompany").val() == null) {
            layer.msg("请选择供应商！");
		}else {
            productIndex = layer.open({
                type: 1 					//Page层类型
                ,area: ['900px', '450px'] 	//宽  高
                ,title: '物料清单'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: $('#productDiv')
                ,end: function () {
                    var formDiv = document.getElementById('productDiv');
                    formDiv.style.display = '';
                }
                ,success: function () {
                    var customer_id = $("#sendCompany").val();
                    table.render({
                        elem: '#productTable'
                        ,url:'${pageContext.request.contextPath}/simple/selectPackingMa.do?customerId='+customer_id
                        ,limits:[10,20,30]
                        ,defaultToolbar:['filter', 'print']
                        ,request: {   //如果无需自定义请求参数，可不加该参数
                            pageName: 'page' //页码的参数名称，默认：page
                            ,limitName: 'limit' //每页数据量的参数名，默认：limit
                        }
                        ,cols: [
                            [{
                                type: 'checkbox',
                                fixed: 'left'
                            }, {
                                field:'id',
                                title:'序号',
                                sort: true,
                                width: 60,
                                type:'numbers',
                                align:'center'
                            }, {
                                field: 'mid',
                                title: 'mid',
                                hide:true
                            }, {
                                field: 'materiel_num',
                                title: 'SAP/QAD',
                                align:'center',
                            }/* , {
	                            field: 'brevity_num',
	                            title: '零件号',
	                            align:'center',
                        	} */, {
                                field: 'materiel_name',
                                title: '中文名称',
                                align:'center',
                            }, {
                                field: 'packing_quantity',
                                title: '包装数量',
                                align:'center',
                            }, {
                                field: 'mBatch',
                                title: '批次',
                                align:'center',
                            }, {
                                field: 'mNum',
                                title: '库存数量',
                                align:'center',
                            }
                            ]
                        ]
                        ,page: false
                    });
                }
            });
		}
    }

    //获取当前时间
    function curentTime() {
        var now=new Date();
        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var time=year+"-"+add0(month)+"-"+add0(day);
        return time;
    }
    
    function add0(m){
        return m<10?'0'+m:m
    }
    
    toastrStyle();
    //获取行索引
    var LayUIDataTable = (function () {
        var rowData = {};
        var $;
        function checkJquery () {
            if (!$) {
                console.log("未获取jquery对象，请检查是否在调用ConvertDataTable方法之前调用SetJqueryObj进行设置！")
                return false;
            } else return true;
        }
        function ConvertDataTable (callback) {
            if (!checkJquery()) return;
            var dataList = [];
            var rowData = {};
            var trArr = $(".layui-table-body.layui-table-main tr");// 行数据
            if (!trArr || trArr.length == 0) {
                console.log("未获取到相关行数据，请检查数据表格是否渲染完毕！");
                return;
            }
            $.each(trArr, function (index, trObj) {
                var currentClickRowIndex;
                var currentClickCellValue;

                $(trObj).click(function (e) {
                    var returnData = {};
                    var currentClickRow = $(e.currentTarget);
                    currentClickRowIndex = currentClickRow.data("index");
                    currentClickCellValue = e.target.innerHTML
                    $.each(dataList[currentClickRowIndex], function (key, obj) {
                        returnData[key] = obj.value;
                    });
                    callback(currentClickRowIndex, currentClickCellValue, returnData);
                });
                var tdArrObj = $(trObj).find('td');
                rowData = {};
                //  每行的单元格数据
                $.each(tdArrObj, function (index_1, tdObj) {
                    var td_field = $(tdObj).data("field");
                    rowData[td_field] = {};
                    rowData[td_field]["value"] = $($(tdObj).html()).html();
                    rowData[td_field]["cell"] = $(tdObj);
                    rowData[td_field]["row"] = $(trObj);

                })
                dataList.push(rowData);
            })
            return dataList;
        }

        return {
            SetJqueryObj: function (jqueryObj) {
                $ = jqueryObj;
            }
            , ParseDataTable: ConvertDataTable
            , HideField: function (fieldName) {
                if (!checkJquery()) return;
                if (fieldName instanceof Array) {
                    $.each(fieldName, function (index, field) {
                        $("[data-field='" + field + "']").css('display', 'none');
                    })
                } else if (typeof fieldName === 'string') {
                    $("[data-field='" + fieldName + "']").css('display', 'none');
                } else {

                }
            }
        }
    })();
</script>
</body>
</html>
